package service

import (
	"database-platform/dal/db"
	"database-platform/logger"
	"database-platform/model"
	"fmt"
)

// GetInstanceList 获取实例列表
func GetInstanceList(params *model.InstanceListRequest) (*model.InstanceListResponse, error) {
	var response = &model.InstanceListResponse{}

	var request = &model.Instance{
		Hostname:   params.Hostname,
		IP:         params.IP,
		Role:       params.Role,
		DBType:     params.DBType,
		ClusterID:  params.ClusterID,
		ShardNum:   params.ShardNum,
		DBVersion:  params.DBVersion,
		DeployType: params.DeployType,
		Env:        params.Env,
		Status:     params.Status,
	}

	result, count, err := db.ListInstanceRecords(request, params.Page, params.PageSize, params.Search, params.ShowCluster, params.ShowServer)
	if err != nil {
		return nil, err
	}
	msg := fmt.Sprintf("[service.GetInstanceList], result: %v, count:%d, request: %v", result, count, request)
	logger.Logger.Warn(msg)

	response.Count = count
	response.Records = result
	response.Page = params.Page
	response.PageSize = params.PageSize

	return response, nil
}

func GetInstanceById(id int) (*model.Instance, error) {
	result, err := db.GetInstanceRecordById(id)
	if err != nil {
		return nil, err
	}
	msg := fmt.Sprintf("[service.GetInstanceById], result: %v,  id: %v", result, id)
	logger.Logger.Warn(msg)

	return result, nil
}

// InsertInstance 插入实例记录
func InsertInstance(instance *model.Instance) error {
	err := db.InsertInstanceRecord(instance)
	if err != nil {
		return err
	}

	msg := fmt.Sprintf("[service.InsertInstance],  instance: %v", instance)
	logger.Logger.Warn(msg)

	return nil
}

// UpdateInstance 更新实例记录
func UpdateInstance(id int, instance *model.Instance) error {
	err := db.UpdateInstanceRecord(id, instance)
	if err != nil {
		return err
	}

	msg := fmt.Sprintf("[service.UpdateInstance],  instance: %v", instance)
	logger.Logger.Warn(msg)

	return nil
}

// DeleteInstance 删除实例记录
func DeleteInstance(id int) error {
	err := db.DeleteInstanceRecord(id)
	if err != nil {
		return err
	}

	msg := fmt.Sprintf("[service.DeleteInstance],  id: %v", id)
	logger.Logger.Warn(msg)

	return nil
}
